package flyingpig.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;

import flyingpig.data.dao.ImageInfoHome;
import flyingpig.data.dao.JobPageHome;
import flyingpig.data.domain.ImageInfo;
import flyingpig.data.domain.JobPage;
import flyingpig.hibernate.HibernateUtil;

/**
 * Servlet implementation class UpdateImageInfo
 */
public class UploadImageInfo extends HttpServlet {
	private static Log logger = LogFactory.getLog(UploadImageInfo.class);
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadImageInfo() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        String concept = request.getParameter("concept");
        String tags = request.getParameter("tags");
        String url = request.getParameter("url");
        String relatedPage = request.getParameter("relatedPage");
        String author = request.getParameter("author");
        String sourcePhotoID = request.getParameter("sourcePhotoID");
        
        if (tags.length() > 1024){
            tags = tags.substring(0, 1023);
        }
        
        int pageID = 0;
        try {
            pageID = Integer.parseInt(request.getParameter("pageID"));
        } catch (Exception e) {
            out.println("status: pageID is wrong");
            out.flush();
            out.close();
            return;
        }
        if (pageID <= 0) {
        	out.println("status: pageID is wrong");
            out.flush();
            out.close();    
            return;
        }
        
        // 有没有相同的image存在 
        ImageInfoHome imageInfoHome = new ImageInfoHome();
        List results = imageInfoHome.findByURL(url);
        if(results.size() > 0){
        	ImageInfo info = (ImageInfo)(results.get(0));
        	logger.info("upload pageID:" + pageID + "failed, because same image has uploaded in pageID:"+ info.getPageId());
			out.println("status: imageInfo exsited");
            out.flush();
            out.close(); 
            return;
        }

        ImageInfo imageInfo = new ImageInfo();
        imageInfo.setConcept(concept);        
        imageInfo.setUrl(url); 
        imageInfo.setTags(tags);
		imageInfo.setAuthor(author);
		imageInfo.setPageId(pageID);
		imageInfo.setRelatedPage(relatedPage);
		imageInfo.setSourcePhotoId(sourcePhotoID);
		imageInfo.setLastUpdate(new Date());
		imageInfo.setCacheState("UNCACHED");

		// 然后开始事务
		boolean res = setImageInfo(imageInfo);

		if (res) {
			out.println("status: upload success");
		} else {
			out.println("status: pageID is wrong");
		}

		out.flush();
		out.close();

	}
    
    synchronized private boolean setImageInfo(ImageInfo imageInfo){   
    	
		Transaction tx = HibernateUtil.getCurrentSession().beginTransaction();
		try {
			// page是否存在
			JobPageHome jobPageHome = new JobPageHome();
			JobPage page = jobPageHome.findById(imageInfo.getPageId());
			if (page == null) {
				logger.info("page wrong");
				return false;
			}

			ImageInfoHome imageInfoHome = new ImageInfoHome();
			imageInfoHome.persist(imageInfo);

			page.setFinishedNum(page.getFinishedNum() + 1);
			page.setLastUpdate(new Date());
			jobPageHome.persist(page);
			tx.commit();
			if(page.getFinishedNum()%100 == 0){
				logger.info("searchJobID:" + page.getSearchJobId() + " | page:"+page.getPage() + " | finishedNum:" + page.getFinishedNum());
			}
			
		} catch (HibernateException e) {

			logger.info("rollback");
			tx.rollback();
			e.printStackTrace();
			return false;
		}
		return true;
    }

}
